$(document).ready(function() {        	    	    
    $('.rate_widget').each(function(i) {
        var widget = this;
        /*
        var out_data = {
            widget_id : $(widget).attr('id'),
            fetch: 1
        };
        */
        var url = document.URL.split('/');
        var car_id = url[url.length - 1];
        var clicked_data = {  
            //clicked_on : 'star_0 ratings_stars',
            widget_id : $(widget).attr('id'),
            car_id : car_id
        };        
        
        $.post(
            base_url + "index.php/rate/submit",
            clicked_data,
            function(INFO) {
                $(widget).data( 'fsr', INFO );
                set_votes(widget);
            },
            'json');
    });
        	
    $('.ratings_stars').hover(        	
        function() {        
            $(this).prevAll().andSelf().addClass('ratings_over');
            $(this).nextAll().removeClass('ratings_vote'); 
        },
        
        // Handles the mouseout
        function() {
            var widget = $(this).parent();
            $(this).prevAll().andSelf().removeClass('ratings_over');
            
            // can't use 'this' because it wont contain the updated data
            //set_votes($(this).parent());
            set_votes(widget);
        }
    );
                
    // This actually records the vote
    $('.ratings_stars').bind('click', function() {        
        var star = this;
        var widget = $(this).parent();
            
        var url = document.URL.split('/');
        var car_id = url[url.length - 1];

        var clicked_data = {
            clicked_on : $(star).attr('class'),
            widget_id : $(star).parent().attr('id'),
            car_id : car_id
        };

        $.post(
            base_url + "index.php/rate/submit",
            clicked_data,
            function(INFO) {
                widget.data( 'fsr', INFO );
                set_votes(widget);
            },
            'json'
        ); 
    });                        
});

function set_votes(widget) {  
    var avg = $(widget).data('fsr').whole_avg;
    var votes = $(widget).data('fsr').number_votes;
    var exact = $(widget).data('fsr').dec_avg;

    $('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
    $('.star_' + avg).nextAll().removeClass('ratings_vote'); 
    $('.total_votes').text( votes + ' votes (' + exact + ' rating)' );
}